<template>
  <div class="publish">
    <div class="flex-column gap10">
      <div>
        <span>代理版本: </span>
        <span>{{ props.data.agentVersion }}</span>
      </div>
      <div>
        <span>可升级版本: </span>
        <span>{{ props.data.allowedVersion }}</span>
      </div>
      <!-- <div>
        <span>本次要升级客户: </span>
        <span>{{ props.data.agentVersion }}</span>
      </div> -->
    </div>

    <div class="flex-row-center-left mgt10 mgb10">
      <div class="flex-row-center-left">
        <div class="no-wrap mgr10">客户名称</div>
        <el-input v-model="state.keyword" style="width: 250px" placeholder="客户名称" clearable>
          <template #append>
            <el-button :icon="Search" @click="handleFilterCustomer" />
          </template>
        </el-input>
      </div>

      <div class="mgl30">已选择{{ state.selectedList.length }}家客户</div>
    </div>

    <div v-loading="state.loading">
      <VxeTable
        ref="tableEl"
        :data="state.dataList"
        border
        header-align="center"
        align="center"
        :scroll-y="{ enabled: true, gt: 8 }"
        max-height="300"
        @checkbox-all="onSelectionChange"
        @checkbox-change="onSelectionChange"
      >
        <vxe-column type="checkbox" width="80" />
        <vxe-column title="客户名称" field="customerName" width="180" />
        <vxe-column title="产线号" field="productionLineId">
          <template #default="{ row }">
            <div class="flex-row-center-between">
              <div class="flex">
                <el-tag v-if="row.selectAll">全部</el-tag>
                <div v-else>
                  <el-tag class="mgr5" v-for="item in row.selectLineList" :key="item.productionLineId">{{ item.productionLineId }}</el-tag>
                </div>
              </div>

              <div>
                <el-dropdown :hide-on-click="false" trigger="click">
                  <el-icon color="#3E72EB" size="25"><CaretBottom /></el-icon>
                  <template #dropdown>
                    <el-dropdown-menu class="publish-header-new-drop">
                      <el-dropdown-item
                        v-for="item in row.list"
                        :key="item.id"
                        style="min-width: 100px"
                        :class="{ active: row.selectLineList.find((d: any) => d.productionLineId === item.productionLineId) }"
                        @click="handleCommand(row, item)"
                      >
                        {{ item.productionLineId }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </template>
        </vxe-column>

        <template #empty>
          <div class="flex-column-center-center">
            <SvgIcon :width="100" :height="100" name="empty-data" color="#606266" />
            <span>暂无数据~</span>
          </div>
        </template>
      </VxeTable>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, watch } from 'vue'
  import { groupBy } from 'xe-utils'
  import type { IAgentEntity } from '@/types'
  import type { AgentVersion } from '../config'
  import request, { type IPage } from '@/service'
  import { Ui } from '@/utils'
  import { Search } from '@element-plus/icons-vue'
  import type { VxeTableInstance } from 'vxe-table'

  const tableEl = ref<VxeTableInstance>()

  interface IProps {
    data: AgentVersion
  }

  const props = withDefaults(defineProps<IProps>(), {
    data: () => ({}) as AgentVersion
  })

  const emits = defineEmits(['publish-success', 'loading-change'])

  const state = reactive({
    loading: false,
    keyword: '',
    dataList: [] as any[],
    selectedList: [] as any[]
  })

  let rawList: any[] = []

  /**----------------------------methods----------------------------------------------------------------------- */

  watch(
    () => state.loading,
    () => {
      emits('loading-change')
    }
  )

  const onSelectionChange = () => {
    const list = tableEl.value?.getCheckboxRecords(true) as any[]
    state.selectedList = list
  }

  const handleCommand = (row: any, v: IAgentEntity) => {
    row.selectAll = false
    const { customerClientId, productionLineId, customerName } = v
    const item = {
      customerClientId,
      productionLineId,
      customerName
    }
    const index = row.selectLineList.findIndex((item: any) => item.productionLineId === v.productionLineId)
    if (index === -1) return row.selectLineList.push(item)
    row.selectLineList.splice(index, 1)
  }

  const handlePublish = () => {
    if (!state.selectedList.length) return Ui.useMessage('warning', '请先勾选客户')

    const agentList = state.selectedList.reduce((list, cur) => {
      if (cur.selectAll) {
        const data = cur.list.map((item: IAgentEntity) => {
          const { customerClientId, productionLineId, customerName } = item
          const infoItem = {
            customerClientId,
            productionLineId,
            customerName
          }

          return infoItem
        })
        list = list.concat(data)
      } else {
        list = list.concat(cur.selectLineList)
      }

      return list
    }, [])

    //@ts-ignore
    // eslint-disable-next-line vue/no-mutating-props
    props.data.agentList = agentList

    request.post('/agent/version/publish', props.data).then(res => {
      if (res.code !== 0) return Ui.useMessage('error', res.msg)
      emits('publish-success')
    })
  }

  const handleFilterCustomer = () => {
    state.dataList = rawList.filter(item => item.customerName.includes(state.keyword))
  }

  const getCustomerList = () => {
    state.loading = true
    const params = {
      current: 1,
      size: 99999,
      agentStatus: '1'
    }

    request
      .get<IPage<IAgentEntity>>('/agent/page', params)
      .then(res => {
        if (res.code !== 0) return Ui.useMessage('error', res.msg)
        const { allowedVersion } = props.data

        const list = Object.entries(groupBy(res.data.records, 'customerName'))

        const mapList = list
          .map(item => {
            return {
              customerName: item[0],
              selectAll: true,
              selectLineList: [],
              list: item[1].filter(i => (allowedVersion ? allowedVersion?.includes(i.agentVersion) : true))
            }
          })
          .filter(item => item.list.length)

        rawList = mapList
        state.dataList = mapList
      })
      .finally(() => (state.loading = false))
  }

  /**----------------------------lifecycle----------------------------------------------------------------------- */

  getCustomerList()

  defineExpose({
    handlePublish
  })
</script>

<style lang="less">
  .publish-header-new-drop .el-dropdown-menu__item:focus,
  .el-dropdown-menu__item:hover {
    background-color: #fff;
    color: #606266;
  }
  .publish-header-new-drop .active:focus,
  .active:hover {
    color: var(--el-color-primary);
  }

  .publish-header-new-drop .active {
    color: var(--el-color-primary);
  }
</style>
